package com.vieewer.btdemo.view.map

import android.graphics.Rect
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.KeyEvent
import android.view.View
import com.vieewer.btdemo.base.BaseActivity
import com.vieewer.btdemo.bean.MapDataBean
import com.vieewer.btdemo.view.gdmap.AMapLaneInfo
import kotlinx.android.synthetic.main.activity_guide_map.*
import java.lang.ref.WeakReference
import android.view.WindowManager
import com.alibaba.fastjson.JSON
import com.lindroid.androidutilskt.extension.putSp
import com.lindroid.androidutilskt.extension.shortToast
import com.nightonke.boommenu.BoomButtons.ButtonPlaceEnum
import com.nightonke.boommenu.BoomButtons.TextInsideCircleButton
import com.nightonke.boommenu.ButtonEnum
import com.nightonke.boommenu.Piece.PiecePlaceEnum
import com.nightonke.boommenu.Util
import com.vieewer.btdemo.R
import com.vieewer.btdemo.bean.SwitchMsgBean
import com.vieewer.btdemo.common.Constants
import com.vieewer.btdemo.utils.*
import kotlinx.android.synthetic.main.activity_guide_map.bmb
import kotlinx.android.synthetic.main.activity_guide_map.driveWayLinear
import java.text.DecimalFormat


class MapGuideActivity :  BaseActivity() {

    //tag for choose menu item
    private var mIndex = 0

    companion object {
        const val MSG_REFRESH_MAP = 0
        const val MSG_REFRESH_MAP_LANEINFO = 1
        var mHandler : MyHandler? = null

        fun refreshView(data : MapDataBean) {
            if (data != null && mHandler != null) {
                var msg = mHandler!!.obtainMessage()
                msg.what = MSG_REFRESH_MAP
                var bundle = Bundle()
                bundle.putSerializable("data", data)
                msg.data = bundle
                mHandler!!.sendMessage(msg)
            }

        }


        fun refreshLaneInfoView(laneInfo : AMapLaneInfo) {
            if (laneInfo != null && mHandler != null) {
                var msg = mHandler!!.obtainMessage()
                msg.what = MSG_REFRESH_MAP_LANEINFO
                var bundle = Bundle()
                bundle.putSerializable("laneInfo", laneInfo)
                msg.data = bundle
                mHandler!!.sendMessage(msg)
            }

        }


    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_guide_map)

        window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
        WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or
        WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        mHandler = MyHandler(this@MapGuideActivity)

        initViews()
        initBoomMenu()
        initListener()

    }

    private fun initListener() {
        txt_log_out.setOnClickListener {
            logOut()
        }

        txt_switch.setOnClickListener {
            putSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, true)
            this.finish()
        }

    }

    private fun initBoomMenu() {
        var imagePadding = Rect(8,8,16,16)
        var dimen = 30
        var imageRect = Rect(dimen,dimen,dimen,dimen)
        bmb.buttonEnum = ButtonEnum.TextInsideCircle
        bmb.piecePlaceEnum = PiecePlaceEnum.DOT_3_1
        bmb.buttonPlaceEnum = ButtonPlaceEnum.SC_3_1

        bmb.addBuilder(
            TextInsideCircleButton.Builder()
                //.normalTextRes(R.string.map_switch_app)
                .normalImageRes(R.drawable.icon_map_switch_app_n)
                .normalTextColorRes(R.color.light_gray2)
                .highlightedImageRes(R.drawable.icon_map_switch_app_h)
                .highlightedTextColorRes(R.color.black)
                .normalColorRes(R.color.white)
                .imagePadding(imagePadding)
                //.imageRect(imageRect)
                .buttonRadius(Util.dp2px(35f))
        )

        bmb.addBuilder(
            TextInsideCircleButton.Builder()
                //.normalTextRes(R.string.map_exit_app)
                .normalImageRes(R.drawable.icon_map_exit_n)
                .normalTextColorRes(R.color.light_gray2)
                .highlightedImageRes(R.drawable.icon_map_exit_h)
                .highlightedTextColorRes(R.color.black)
                .normalColorRes(R.color.white)
                .imagePadding(imagePadding)
                //.imageRect(imageRect)
                .buttonRadius(Util.dp2px(35f))

        )


        bmb.addBuilder(
            TextInsideCircleButton.Builder()
                .normalImageRes(R.drawable.icon_map_cancel_n)
                //.normalTextRes(R.string.map_cancel)
                .normalTextColorRes(R.color.light_gray2)
                .highlightedImageRes(R.drawable.icon_map_cancel_h)
                .highlightedTextColorRes(R.color.black)
                .normalColorRes(R.color.white)
                .imagePadding(imagePadding)
                //.imageRect(imageRect)
                .buttonRadius(Util.dp2px(35f))
        )


    }

    private fun initViews() {
        var bean = intent.getSerializableExtra("data")
        if (bean != null) {
            refreshViewUI(bean as MapDataBean)
        }

        var laneInfoData = intent.getSerializableExtra("laneInfoData")
        if (laneInfoData != null) {
            refreshLaneInfoView(laneInfoData as AMapLaneInfo)
        }
    }


    fun refreshViewUI(bean: MapDataBean) {

        var resId = MapUtils.getDrawableRes(bean.directionType)
        if (resId > 0) {
            img_direction.setImageDrawable(ContextCompat.getDrawable(this, resId))
        }

        /*if (bean.directionType != null && bean.directionType != "") {
            img_direction.setImageBitmap(CommonUtils.sendImage(bean.directionType))
        }*/

        if (bean.roadName != null) {
            txt_road.visibility = View.VISIBLE
            txt_road.text = "进入" + bean.roadName
        } else {
            txt_road.visibility = View.INVISIBLE
        }

        if (bean.leftTime != null &&  bean.leftTime != "") {
            txt_left_time.visibility = View.VISIBLE
            txt_left_time.text = "剩余" + Math.ceil(bean.leftTime.toDouble() / 60).toInt() + "分钟"
            //txt_left_time.text = "剩余" + bean.leftTime
        } else {
            txt_left_time.visibility = View.INVISIBLE
        }

        if (bean.LeftDistance != null &&  bean.LeftDistance != "") {

            //val result = BigDecimal(bean.LeftDistance.toInt() / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).toDouble()
            var result = ""
            result = if (bean.LeftDistance.toInt() < 1000) {
                bean.LeftDistance.toInt().toString() + "米"
            } else {
                val df = DecimalFormat("#.00")
                df.format(bean.LeftDistance.toInt() / 1000f) + "公里"
            }

            txt_left_miles.text = result
            txt_left_miles.visibility = View.VISIBLE
            //txt_left_miles.text = bean.LeftDistance
        } else {
            txt_left_miles.visibility = View.INVISIBLE
        }

        if (bean.leftNesctRoadDiastance != null) {
            txt_value_miles.visibility = View.VISIBLE
            txt_value_miles.text = bean.leftNesctRoadDiastance
        } else {
            txt_value_miles.visibility = View.INVISIBLE
        }

    }

    fun refreshLaneInfoViewUI(data : AMapLaneInfo) {
        Log.i("yjj", "refreshLaneInfoViewUI ~~~~~")
        driveWayLinear.buildDriveWay(data)
    }




    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {

        Log.i("yjj", "MapGuideActivity onKeyUp >>> keyCode"
                + keyCode + ", action =" + event!!.action + ", isBoomed =" + bmb.isBoomed)

        if (bmb.isBoomed) {
            when(keyCode) {

                22 -> {  //往前滑动触控板
                    mIndex ++
                    setCheckedItemUI()
                }


                21 -> {  //往后滑动触控板
                    mIndex --
                    setCheckedItemUI()
                }

            }
            Log.i("yjj", "real index >>>" + mIndex % 3)

        }



        return super.onKeyUp(keyCode, event)

    }

    private fun setCheckedItemUI() {

        when ( mIndex % 3 ) {

            1 -> {

                (bmb.getBoomButton(0) as TextInsideCircleButton).toHighlighted()
                (bmb.getBoomButton(1) as TextInsideCircleButton).toNormal()
                (bmb.getBoomButton(2) as TextInsideCircleButton).toNormal()

            }

            2 -> {
                (bmb.getBoomButton(1) as TextInsideCircleButton).toHighlighted()
                (bmb.getBoomButton(0) as TextInsideCircleButton).toNormal()
                (bmb.getBoomButton(2) as TextInsideCircleButton).toNormal()

            }

            0 -> {
                (bmb.getBoomButton(2) as TextInsideCircleButton).toHighlighted()
                (bmb.getBoomButton(0) as TextInsideCircleButton).toNormal()
                (bmb.getBoomButton(1) as TextInsideCircleButton).toNormal()
            }
        }



    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        if( keyCode == KeyEvent.KEYCODE_BACK ) {

            mIndex = 0
            bmb.boom()
            Log.i("yjj", "mapGuideActivity show menu ~~~")

            return true //不执行父类点击事件
        }


        if (keyCode == 66) {
            operateIndexFun()
        }



        return super.onKeyDown(keyCode, event)

    }

    private fun operateIndexFun() {

        Log.i("yjj", "goto index ="+ mIndex % 3)

        when (mIndex % 3) {

            1 -> {  //切换应用 如果返回到菜单，等待>1分钟，则发送给手机取消导航。
                putSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, true)
                putSp(Constants.SP_KEY_SHOW_MAP_GUIDE_AGAIN_INSTANTLY_TAG, false)
                this.finish()
            }

            2 -> {  //退出
                logOut()
            }

            0 -> {  //取消
                bmb.reboom()
            }

        }


    }

    private fun logOut() {
        putSp(Constants.SP_KEY_MAP_GUIDE_SWITCH_APP, false)
        sendToFinishMapGuide()
        shortToast("退出导航")
        Handler().postDelayed({
            this.finish()
        }, 1*1000)

    }

    private fun sendToFinishMapGuide() {

        val data = SwitchMsgBean()
        data.type = "finishMap"
        val dataStr = JSON.toJSONString(data)
        LogUtil.e("yjj", "sendSuccessToPhone finish map guide ~~~")
        CommunicateToPhoneHelper.instance.write(dataStr)

    }


    /**
     * 声明一个静态的Handler内部类，并持有外部类的弱引用
     */
    class MyHandler constructor(activity: MapGuideActivity) : Handler() {

        private val mActivity: WeakReference<MapGuideActivity> = WeakReference<MapGuideActivity>(activity)

        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg!!.what) {

                MSG_REFRESH_MAP -> {
                    mActivity.get()!!.refreshViewUI(msg!!.data.getSerializable("data") as MapDataBean)
                }
                MSG_REFRESH_MAP_LANEINFO -> {
                    mActivity.get()!!.refreshLaneInfoViewUI(msg!!.data.getSerializable("laneInfo") as AMapLaneInfo)
                }

            }
        }

    }



    override fun onDestroy() {
        super.onDestroy()
        mHandler!!.removeCallbacksAndMessages(null)
    }




}